package com.bcu.calculus.service.serviceImpl;

import com.bcu.calculus.entity.*;
import com.bcu.calculus.mapper.*;
import com.bcu.calculus.service.UserInfoService;
import com.bcu.calculus.utils.BranchUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@Service
public class UserInfoServiceImpl implements UserInfoService {
    private Logger logger= LoggerFactory.getLogger(getClass());

    @Resource
    private UserinfoMapper userinfoMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private SendMapper sendMapper;

    @Resource
    private FlistMapper flistMapper;

    @Resource
    private SlistMapper slistMapper;

    @Resource
    private TlistMapper tlistMapper;

    @Resource
    private TotalMapper totalMapper;


    @Override
    public Message<?> AddUserInfo(UserInfo userInfo) {

        User user = userMapper.selectByPrimaryKey(userInfo.getUserId());



        if (user == null){
            logger.info("用户信息-----添加用户信息成功,userId为 "+userInfo.getUserId());
            return userinfoMapper.insertSelective(userInfo) > 0 ? Message.success(null) : Message.fail(null);
        }else{
            logger.info("用户信息-----添加用户信息，用户信息已存在");
            return Message.fail("用户信息已存在");
        }

    }

    @Override
    public Message<?> deleteUserInfo(String userId) {
        logger.info("用户信息-----删除用户信息,userId为 "+userId);
        return userinfoMapper.deleteByPrimaryKey(userId) > 0 ? Message.success(null) : Message.fail(null);
    }

    @Override
    public Message<?> updateUserInfoByPrimaryKeySelective(UserInfo userInfo) {
        User user = userMapper.selectByPrimaryKey(userInfo.getUserId());

        if (user == null){
            logger.info("用户信息------尝试修改用户信息,但是用户不存在,修改失败,尝试修改的用户userId为 "+userInfo.getUserId());
            return Message.fail("用户不存在");
        }else {
            logger.info("用户信息-----修改用户信息,userId为 "+userInfo.getUserId());
            return Message.success(null).add(userinfoMapper.updateByPrimaryKeySelective(userInfo));

        }
    }

    @Override
    public Message<UserInfo> selectUserInfoByUserId(String userId) {

        User user = userMapper.selectByPrimaryKey(userId);

        if (user == null){
            logger.info("用户信息-----通过userId查找用户信息 失败,用户不存在,userId为 "+userId);
            return Message.fail("用户不存在");
        }else {
            logger.info("用户信息-----通过userId查找用户信息,userId为 "+userId);
            return Message.success(null).add(userinfoMapper.selectByPrimaryKey(userId));

        }
    }

    @Override
    public Message<List<UserInfo>> findAllUserInfo() {
        logger.info("用户信息-----查找全部用户信息");
        return Message.success(null).add(userinfoMapper.findAllUserInfo());
    }

    @Override
    public Message<List<UserInfo>> slectByUserName(String userName) {
        logger.info("用户信息-----通过用户名查找,userName为 "+userName);
        return Message.success(null).add(userinfoMapper.slectByUserName(userName));
    }

    @Override
    public Message<List<UserInfo>> selectAvgScoreByUserBranch(Integer userBranch) {
        String str = userBranch.toString();
        logger.info("用户信息-----按党小组得到平均分");
        return Message.success("操作成功,前端的伙伴们请注意!!!!!!!!!!!!userScore为平均分").add(userinfoMapper.selectAvgScoreByUserBranch(str));
    }

    @Override
    public Message<List<UserInfo>> selectPRByUserBranch(Integer userBranch) {
        String str = userBranch.toString();
        logger.info("用户信息-----按党小组得到及格率");
        return Message.success("操作成功,前端的伙伴们请注意!!!!!!!!!!!!userScore为及格率").add(userinfoMapper.selectPRByUserBranch(str));
    }

    @Override
    public Message<List<UserInfo>> selectAllBranchPR() {
        logger.info("用户信息-----得到所有党小组及格率");
        return Message.success("操作成功,前端的伙伴们请注意!!!!!!!!!!!!userScore为及格率,userBranch为党小组号").add(userinfoMapper.selectAllBranchPR());
    }

    @Override
    public Message<List<UserInfo>> selectALLBranchAvgScore() {
        logger.info("用户信息-----得到所有党小组平均分");
        return Message.success("操作成功,前端的伙伴们请注意!!!!!!!!!!!!userScore为平均分userBranch为党小组号").add(userinfoMapper.selectALLBranchAvgScore());
    }

    @Override
    public Message<List<UserInfo>> selectAllPR() {
        return Message.success("操作成功,前端的伙伴们请注意!!!!!!!!!!!!userScore为及格率").add(userinfoMapper.selectAllPR());
    }

    @Override
    public Message<List<UserInfo>> selectAllAV() {
        return Message.success("操作成功,前端的伙伴们请注意!!!!!!!!!!!!userScore为平均分").add(userinfoMapper.selectAllAV());
    }

    @Override
    public List<UserInfoBranch> showSend(String flistId, String slistId, String tlsitId, String sendSemseterId) {
        List<UserInfo> userInfoList = userinfoMapper.showSend(flistId,slistId,tlsitId,sendSemseterId);
        List<UserInfoBranch> userInfoBranchList = new ArrayList<UserInfoBranch>();
        for (UserInfo userInfo:userInfoList){
            UserInfoBranch branch = new UserInfoBranch();
            branch.setSend(userInfo.getSend());
            branch.setUserId(userInfo.getUserId());
            branch.setUserName(userInfo.getUserName());
            branch.setUserBranch(BranchUtil.toHanStr(userInfo.getUserBranch()));
            userInfoBranchList.add(branch);
        }
        return userInfoBranchList;
    }

    @Override
    public List<UserInfoBranch> showSendLikeName(String flistId, String slistId, String tlistId, String sendSemseterId, String likeName) {
        List<UserInfo> userInfoList = userinfoMapper.showSendLikeName(flistId,slistId,tlistId,sendSemseterId,likeName);
        List<UserInfoBranch> userInfoBranchList = new ArrayList<>();
        for (UserInfo userInfo:userInfoList){
            UserInfoBranch branch = new UserInfoBranch();
            branch.setSend(userInfo.getSend());
            branch.setUserId(userInfo.getUserId());
            branch.setUserName(userInfo.getUserName());
            branch.setUserBranch(BranchUtil.toHanStr(userInfo.getUserBranch()));
            userInfoBranchList.add(branch);
        }
        return userInfoBranchList;
    }

    @Override
    public Message<?> getAllUserScoreThisSemId(Integer semId) {
        List<UserInfo> userList =  userinfoMapper.getAllUserScoreThisSemId(semId);
        List<HashMap<String,Object>> maps = new ArrayList<>();


        for (UserInfo userinfo:userList) {
            Double sumofone = 0.0;
            ScoreUserInfo scoreUserInfo = new ScoreUserInfo();
            scoreUserInfo.setUserInfo(userinfo);
            List<listF> listFLis = getFlistTolistF(semId,userinfo.getUserId());
            for (listF F:listFLis) {
                //System.out.print(F.getFlistId()+":"+F.getFListScore()+"\n");
                sumofone += F.getFListScore();
            }
            scoreUserInfo.setSumScore(sumofone);


            HashMap<String,Object> map = new HashMap<>();
            map.put("userId",userinfo.getUserId());
            map.put("userName",userinfo.getUserName());
            map.put("userBranch",BranchUtil.toHanStr(userinfo.getUserBranch()));
            if (userinfo.getTotal()!=null){
                map.put("totalScore",userinfo.getTotal().getTotalScore());
            }else {
                map.put("totalScore",null);
                map.put("sendScoreStatus","未发布");
            }

            map.put("sendScore",scoreUserInfo.getSumScore());
            if (map.get("totalScore")!=null){
                if (sumofone.compareTo((Double)map.get("totalScore"))==0){
                    map.put("sendScoreStatus","已发布");
                }else {
                    map.put("sendScoreStatus","未发布");
                }
            }
            maps.add(map);
        }


        return Message.success(null).add(maps);
    }

    @Override
    public Message<?> getOneUserScoreThisSemId(Integer semId, String userId) {
        UserInfo userInfo = userinfoMapper.selectByPrimaryKey(userId);
        Total total = totalMapper.selectOneByUserId(userId,semId);
        userInfo.setTotal(total);
        Double sumofone = 0.0;
        ScoreUserInfo scoreUserInfo = new ScoreUserInfo();
        scoreUserInfo.setUserInfo(userInfo);
        List<listF> listFLis = getFlistTolistF(semId,userInfo.getUserId());
        for (listF F:listFLis) {
            //System.out.print("Flist:"+F.getFlistId()+":"+F.getFListScore()+"\n");
            sumofone += F.getFListScore();
        }
        scoreUserInfo.setSumScore(sumofone);

        HashMap<String,Object> map = new HashMap<>();
        map.put("userId",userInfo.getUserId());
        map.put("userName",userInfo.getUserName());
        map.put("userBranch",BranchUtil.toHanStr(userInfo.getUserBranch()));
        if (userInfo.getTotal()!=null){
            map.put("totalScore",userInfo.getTotal().getTotalScore());
        }else {
            map.put("totalScore",null);
            map.put("sendScoreStatus","未发布");
        }


        map.put("sendScore",scoreUserInfo.getSumScore());
        if (map.get("totalScore")!=null){
            if (sumofone.compareTo((Double)map.get("totalScore"))==0){
                map.put("sendScoreStatus","已发布");
            }else {
                map.put("sendScoreStatus","未发布");
            }
        }
        return Message.success(null).add(map);
    }



    //将所有的Flist变成lsitF
    private List<listF> getFlistTolistF(Integer semId,String userId){
        List<Flist> flistList = flistMapper.selectAllFlist();
        List<listF> listFList = new ArrayList<>();
        for (Flist one:flistList) {
            listF listF = new listF();
            listF.setFlistId(one.getFlistId());
            listF.setMaxScore(one.getFlistMaxScore());
            listF.setMinScore(one.getFlistMinScore());
            listF.setSlists(getSlistTolistSByFlistID(one.getFlistId(),semId.toString(),userId));

            //如果一级没有二级子路由
            if(listF.getSlists().isEmpty()){
                Send Fsend = sendMapper.getSendByManyListAndSemseterIdAndUserId(one.getFlistId(),"nolook","nolook",semId.toString(),userId);
                if (Fsend == null){
                    listF.setFListScore(0.0);
                }else {
                    listF.setFListScore(Fsend.getSendScore());
                }
            }else{  //有子节点
                    Double Fscore = 0.0;
                    for (listS S:listF.getSlists()) {
                        if (S.getSListScore()!=null){
                            //System.out.print("++Slist:"+S.getSlistId()+":"+S.getSListScore()+"\n");
                            Fscore = Fscore+S.getSListScore();
                        }
                    }
                    listF.setFListScore(Fscore);
                    if (Fscore>listF.getMaxScore()){
                        listF.setFListScore(listF.getMaxScore());
                    }else if (Fscore<listF.getMinScore()){
                        listF.setFListScore(listF.getMinScore());
                    }else {

                        listF.setFListScore(Fscore);
                    }
                }
            listFList.add(listF);
            }

        return listFList;
    }

    //根据一级路由将所有的Slist变成lsitS
    private List<listS> getSlistTolistSByFlistID(String FlistID,String semId,String userId){
        List<Slist> slistList = slistMapper.getSlistByFlistId(FlistID);
        List<listS> listSList = new ArrayList<>();
        for (Slist one:slistList) {
            listS listS = new listS();
            listS.setSlistId(one.getSlistId());
            listS.setMaxScore(one.getSlistMaxScore());
            listS.setMinScore(one.getSlistMinScore());
            listS.setTlists(tlistMapper.getTlistBySlistId(one.getSlistId()));

            if (listS.getTlists().isEmpty()){
                Send Ssend = sendMapper.getSendByManyListAndSemseterIdAndUserId(FlistID,one.getSlistId(),"nolook",semId,userId);
                if (Ssend == null){
                    listS.setSListScore(0.0);
                }else {
                    listS.setSListScore(Ssend.getSendScore());
                }
            }else{
                Double Sscore = 0.0;
                for (Tlist T:listS.getTlists()) {
                    Send Tsend = sendMapper.getSendByManyListAndSemseterIdAndUserId(FlistID,one.getSlistId(),T.getTlistId(),semId,userId);
                    if (Tsend!=null&&Tsend.getSendScore()!=null){
                        //System.out.print("++++Tlist"+Tsend.getSendTlistId()+":"+Tsend.getSendScore()+"\n");
                        Sscore += Tsend.getSendScore();
                    }
                }
                    if (Sscore>listS.getMaxScore()){
                        listS.setSListScore(listS.getMaxScore());
                    }else if (Sscore<listS.getMinScore()){
                        listS.setSListScore(listS.getMinScore());
                    }else {
                        listS.setSListScore(Sscore);
                    }

            }

            listSList.add(listS);
        }

        return listSList;
    }


}
